package com.zbkj.common.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import org.apache.commons.lang3.StringUtils;

public class ChineseCharacterUtil {

    /**
     * 将汉字转成拼音(取首字母或全拼)
     * ^[\u2E80-\u9FFF]+$ 匹配所有东亚区的语言
     * ^[\u4E00-\u9FFF]+$ 匹配简体和繁体
     * ^[\u4E00-\u9FA5]+$ 匹配简体
     *
     * @param content
     * @return
     */
    public static String getFirstLetter(String content) {
        if (content == null || "".equals(content.trim())) {
            return "#";
        }
        String result = StringUtils.EMPTY;
        String first = String.valueOf(content.charAt(0));
        if (first.matches("^[\u2E80-\u9FFF]+$")) {
            result = convert(content.charAt(0));
        } else if (first.matches("^[a-zA-Z]+$")) {   //判断是不是字母
            result = first;
        }
        return StringUtils.isBlank(result) ? "#" : result.toUpperCase();
    }

    /***
     * 将单个汉字转成拼音
     * @param c
     * @return
     */
    private static String convert(char c) {
        HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        try {
            String[] res = PinyinHelper.toHanyuPinyinStringArray(c, outputFormat);
            return String.valueOf(res[0].charAt(0)).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static void main(String[] args) {
        System.out.println(getFirstLetter("한국어#愛A123"));
        System.out.println(getFirstLetter("愛A123"));
        System.out.println(getFirstLetter("我A123"));
        System.out.println(getFirstLetter("!#A123"));
        System.out.println(getFirstLetter("A123"));
        System.out.println(getFirstLetter("123"));
        System.out.println(getFirstLetter("！！！123"));
    }
}
